import { getDeviceListAll } from "@/api/modules/iot/device";
import { deptAnonymous } from "@/utils/constants";
import { getCurrentInstance, defineComponent, ComponentInternalInstance } from "vue";
export default defineComponent({
	props: {
		modelValue: [String, Number, Array],
		multiple: Boolean,
		disabled: Boolean,
		detail: {
			type: Object,
			default() {
				return {};
			}
		}
	},
	emits: ["update:modelValue"],
	setup(props, { emit, expose }) {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const state = reactive<any>({
			selected: props.multiple ? [] : "",
			dataList: []
		});
		onMounted(() => {
			init();
		});
		const init = async () => {
			let res = await getDeviceListAll({
				pageIndex: 1,
				pageSize: 9999,
				deptIdNot: deptAnonymous,
				productModel: props.detail.productId
			});
			state.dataList = res.result?.records || [];
			state.selected = props.modelValue;
		};
		watch(
			() => props.modelValue,
			() => {
				state.selected = props.modelValue;
			}
		);
		const selectEl = ref();
		const change = () => {
			props.detail.devSn = state.selected;
			selectEl.value.blur();
			emit("update:modelValue", state.selected);
		};
		expose({ init });
		return () => {
			return (
				<>
					<div class="w-full">
						<el-select
							ref={selectEl}
							class="w-full"
							disabled={props.disabled}
							multiple={props.multiple}
							collapse-tags
							collapse-tags-tooltip
							v-model={state.selected}
							placeholder={proxy?.$t("selectdevicelistall.placeholder")}
							onChange={() => change()}
							clearable
							filterable
						>
							{state.dataList.map((item: any) => {
								return (
									<el-option label={item.name || item.sn} value={item.sn}>
										<div class="flex justify-between">
											<div class="pr-4">{item.name || item.sn}</div>
											{item.name == item.sn ? "~" : <div class="text-gray-400">{item.sn}</div>}
										</div>
									</el-option>
								);
							})}
						</el-select>
					</div>
				</>
			);
		};
	}
});
